package portal.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import beans.BaseResourceState;
import beans.FullJobState;
import beans.HttpConfig;
import beans.HttpResult;
import beans.HttpResultList;
import engine.BIEngine0_1.AlgorithmOperator;
import portal.cmd.JHCmd;
import portal.dao.ScheduleClusterHostDao;
import portal.engine.JobOperator;
import utils.FileOper;

/**
 * Created with IDEA
 * author:HMY
 * Date:2018/10/29
 * Time:18:46
 * //TODO 定时更新计算节点
 */
@Service
@EnableScheduling
public class IntervalUpdateHost implements SchedulingConfigurer {

    public static final Logger logger = LoggerFactory.getLogger(IntervalUpdateHost.class);
    private String token;
    public static String cron = "0/15 * * * * ?";
    @Autowired
    public ScheduleClusterHostDao scheduleClusterHostDao ;
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            /**
             * 开始进行更新计算节点信息
             */
            @Override
//            @Scheduled
            public void run() {
                //从服务器获取token
                HttpResult tokenResult = JobOperator.getToken(HttpConfig.userName, HttpConfig.passWord);
                if (tokenResult.isResult()) {
                    token = tokenResult.getMessage();
                }
                if(!HttpConfig.fake) {
                    //基础设施资源监控，获取全部基础设施资源信息
                    HttpResultList httpResultList = AlgorithmOperator.getJobBasicState(token);
                    for (int i = 0; i < httpResultList.getDatas().size(); i++) {
                        BaseResourceState baseResourceState = (BaseResourceState) httpResultList.getDatas().get(i);
                        /*if (scheduleClusterHostDao.isHostByHostName(baseResourceState.getHostName())) {
                            //如果存在这个节点，就更新它的信息
                            scheduleClusterHostDao.updateHostDetail(baseResourceState);
                        } else {
                            //如果不存在这个节点，就插入这个节点
                            scheduleClusterHostDao.insertHostDetail(baseResourceState);
                        }*/
                        //由于需要历史节点信息，所以不进行判断直接插入
                        scheduleClusterHostDao.insertHostDetail(baseResourceState);
                    }
                    checkExclusiveJobEnd();
                    
                }else{
                    logger.debug(".....this is a interval task of update host...");
                }

            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 任务触发，可修改任务的执行周期
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }

    public IntervalUpdateHost(){

        //每次程序启动时获取core
        Properties httpPro = new Properties();
        try {
            httpPro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("http.properties"));
            String updateHostTime = httpPro.getProperty("updateHostTime");  //以分钟为单位
            cron = "0 0/" + updateHostTime + " * * * ?";
            logger.debug("The Update Time = "+updateHostTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //开启线程模拟在项目运行中改变时间间隔
       /* new Thread(new Runnable() {
            @Override
            public void run() {
//                while(true) {
                    Properties httpPro = new Properties();
                    try {
                        httpPro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("http.properties"));
                        String updateHostTime = httpPro.getProperty("updateHostTime");  //以分钟为单位
                        cron = "0 0/" + updateHostTime + " * * * ?";
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                }
            }
        }).start();*/
      /*  new Thread(new Runnable(){
            @Override
            public void run() {
//                for(int i=2;i<=3;i++) {
                    //模拟改变时间间隔
                    String path = Thread.currentThread().getContextClassLoader().getResource("http.properties").getPath();
                    System.out.println(path);
                    //path = path.split("target")[0];
                    Properties pro = new Properties();
                    FileOutputStream ofile = null;
                    try {
                        ofile = new FileOutputStream(path + "http.properties", true);
                        pro.setProperty("updateHostTime", String.valueOf(pro.getProperty("updateHostTime")));
                        pro.store(ofile, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            ofile.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                }
            }
        }).start();*/
    }
public void checkExclusiveJobEnd(){
	if(HttpConfig.modelIds==null||HttpConfig.modelIds.length()<=2){
		return;
	}
	String[] modelIds = HttpConfig.modelIds.split("#");
	for(String modelId:modelIds){
		if(modelId==null||modelId.length()==0)continue;
		//
		//
		String fName=HttpConfig.taskJsonFileUri+modelId+"_exclusiveNode.json";
		File file= new File(fName);
		if(file.exists()){
			String jobs=FileOper.readFile(fName);
			if(jobs==null || jobs.length()==0)
				continue;
			String[] jIds= jobs.split("#");
			int count=0;
			count = openExecHost(jIds, count);
			if(count!=0 && count== jIds.length){
				file.delete();
			}
			
		}
	}
}

private int openExecHost(String[] jIds, int count) {
	for(String id:jIds){
		HttpResultList httpResultList;
		try {
			httpResultList = JobOperator.getScheduleJobFullState(id, JobOperator.getToken(HttpConfig.userName, HttpConfig.passWord).getMessage());
			FullJobState fullJobState = (FullJobState) httpResultList.getDatas().get(0);
			switch(fullJobState.getStatus().trim()){
				case "EXIT":
				case "DONE":{
					JHCmd  j=new JHCmd();
					j.hostOpen(fullJobState.getExecutionHost().split("]")[0].replaceAll("[\"\\[]", ""));
					count ++;
				}break;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	return count;
}
    public static void main(String[] args) {
    	String[] aa=FileOper.readFile("/home/beirut/Documents/taskJsontest.json").split("#");
    	System.out.println(aa.length);
    	for(String a:aa){
    		System.out.println(a.length());
    	}
    	StringBuilder sb=new StringBuilder();
    	//System.out.println(sb.toString().length());
    	FileOper.writeFile("/home/beirut/Documents/taskJsontest.json",FileOper.readFile("/home/beirut/Documents/taskJsontest.json")+ "237#");
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("thread aaaaaa");
//            }
//        }).start();
//        new Thread(new Runnable() {1
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(5000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("thread bbbbbbbbb");
//            }
//        }).start();
    }

}